// src/components/RegisterForm.jsx
import { Form, Input, Button, message } from 'antd';
import { register } from '../services/auth'; // 注意文件名为auth
import { useNavigate } from 'react-router-dom';

export default function RegisterForm() {
  const navigate = useNavigate();

  const onFinish = async (values) => {
    try {
      await register(values.email, values.password, values.username);
      message.success('注册成功');
      navigate('/');
    } catch (err) {
      message.error('注册失败，可能邮箱已被注册');
    }
  };

  return (
    <Form name="register" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} onFinish={onFinish}>
      <Form.Item
        label="邮箱"
        name="email"
        rules={[
          { required: true, message: '请输入邮箱' },
          { type: 'email', message: '请输入有效的邮箱地址' },
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="用户名"
        name="username"
        rules={[{ required: true, message: '请输入用户名' }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="密码"
        name="password"
        rules={[{ required: true, message: '请输入密码' }]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item
        label="确认密码"
        name="confirm"
        dependencies={['password']}
        hasFeedback
        rules={[
          { required: true, message: '请再次输入密码' },
          ({ getFieldValue }) => ({
            //validator是一个函数，在输入内容时调用该函数，检验二次输入的密码是否和第一次一样
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('两次输入的密码不一致'));
            },
          }),
        ]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
        <Button type="primary" htmlType="submit" block>
          注册
        </Button>
        <div style={{ marginTop: '10px', textAlign: 'right' }}>
          <a href="/">返回登录页面</a>
        </div>
      </Form.Item>
    </Form>
  );
}
